package minuy.android.jsdj2020;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;

import java.util.Arrays;
import java.util.Locale;

import minuy.android.jsdj2020.bean.AccelerationBean;
import minuy.android.jsdj2020.view.ChartViewTool;
import minuy.android.jsdj2020.view.DynamicLineChartManager;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, SensorEventListener{

    static final int CHANGE_ACC = 1;  // 加速度改变
    static final int PLAY_STA = 2;  // 监听传感器状态改变

    // 图表
    LineChart ctMain;
    // 数据文本
    TextView tvAx,tvAy,tvAz,tvDataCount;
    // 按钮
    Button btnSetting,btnDataList,btnSave;

    Sensor sensor;
    SensorManager sensorManager;

    long accCount;

    DynamicLineChartManager dynamicLineChartManager;

    ImageButton btnPause;

    TextView tvTitle;

    boolean isListen = false;

    private final Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case CHANGE_ACC:
                    AccelerationBean accelerationBean = (AccelerationBean) msg.obj;
                    updateData(accelerationBean, true);
                    break;

                case PLAY_STA:
                    if(isListen){
                        tvTitle.setText(R.string.started);
                        btnPause.setImageResource(android.R.drawable.ic_media_pause);
                    }else{
                        tvTitle.setText(R.string.not_started);
                        btnPause.setImageResource(android.R.drawable.ic_media_play);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        accCount = 0;

        // 初始化视图
        ctMain = findViewById(R.id.ctMain);

        tvAx = findViewById(R.id.tvAx);
        tvAy = findViewById(R.id.tvAy);
        tvAz = findViewById(R.id.tvAz);
        tvDataCount = findViewById(R.id.tvDataCount);
        tvTitle = findViewById(R.id.tvTitle);

        btnSetting = findViewById(R.id.btnSetting);
        btnDataList = findViewById(R.id.btnDataList);
        btnSave = findViewById(R.id.btnSave);
        btnPause = findViewById(R.id.btnPause);
        btnPause.setOnClickListener(this);

        // 初始化图表
        dynamicLineChartManager = new DynamicLineChartManager(ctMain, new String[]{"X", "Y", "Z"}, new Integer[]{Color.RED, Color.GREEN, Color.BLUE});

        updateData(new AccelerationBean(0, 0, 0), false);
    }


    /**
     * 更新UI数据
     * @param accelerationBean 加速度传感器数据
     * @param isUpdateChart 是否更新图表
     */
    private void updateData(AccelerationBean accelerationBean, boolean isUpdateChart){
        if(accelerationBean == null){
            return;
        }

        if(tvAx!=null) {
            tvAx.setText(String.format(getResources().getString(R.string.ax), String.format(Locale.CHINA, "%.2f", accelerationBean.getX())));
        }

        if(tvAy!=null) {
            tvAy.setText(String.format(getResources().getString(R.string.ay) ,String.format(Locale.CHINA,"%.2f", accelerationBean.getY())));
        }

        if(tvAz!=null) {
            tvAz.setText(String.format(getResources().getString(R.string.az) ,String.format(Locale.CHINA,"%.2f", accelerationBean.getZ())));
        }

        if(tvDataCount!=null) {
            tvDataCount.setText(String.format(getResources().getString(R.string.data_count), accCount));
        }

        if(ctMain != null && isUpdateChart){
            Float[] fs = new Float[]{accelerationBean.getX(), accelerationBean.getY(), accelerationBean.getZ()};
            dynamicLineChartManager.addEntry(Arrays.asList(fs));
        }
    }

    /**
     * 开始监听传感器
     */
    private void upSensor(){
        // 初始化传感器
        try{
            sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_UI);
            isListen = true;
        }catch(Exception e){
            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 取消传感器监听
     */
    private void downSensor(){
        isListen = false;
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        accCount++;

        //event里保存的是手机x，y，z的坐标，具体可以去网上看看图片
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        AccelerationBean accelerationBean = new AccelerationBean(x, y, z);

        Message msg = new Message();
        msg.what = CHANGE_ACC;
        msg.obj = accelerationBean;

        handler.sendMessage(msg);
    }

    @Override
    public void onAccuracyChanged(Sensor p1, int p2)
    {
        // TODO: Implement this method
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        Message msg = new Message();

        if(v.getId() == R.id.btnPause) {
            if(isListen){
                downSensor();
            }else{
                upSensor();
            }
            msg.what = PLAY_STA;
        }

        handler.sendMessage(msg);
    }
}